package com.feihong.yw189.paidan.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.astuetz.PagerSlidingTabStrip;
import com.feihong.yw189.R;
import com.feihong.yw189.bluetooth.dialog.MyUsualyDialog;
import com.feihong.yw189.bluetooth.utils.util.ConstantsValue;
import com.feihong.yw189.bluetooth.utils.util.PrefUtils;
import com.feihong.yw189.bluetooth.utils.util.ToastUtils;
import com.feihong.yw189.fragment.base.BaseFragment;
import com.feihong.yw189.paidan.activity.DispatchActivity;
import com.feihong.yw189.paidan.adapter.JieDanOrderAdapter;
import com.feihong.yw189.paidan.inter.LiuDanListener;
import com.feihong.yw189.paidan.qiangdanservice.JieDanTools;
import com.feihong.yw189.paidan.qiangdanservice.daemonservice.IntentWrapper;
import com.feihong.yw189.paidan.qiangdanservice.newversion.DaemonService;
import com.feihong.yw189.paidan.qiangdanservice.newversion.GlobalController;
import com.feihong.yw189.paidan.qiangdanservice.newversion.PaiDanRemoteService;
import com.feihong.yw189.paidan.view.NestingViewPager;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * 接单
 * 张鹏
 * 2018.2
 */
@RuntimePermissions
public class DispatchHome extends BaseFragment {

    private static final String TAG = "派单";
    private DispatchActivity mActivity;
    private TextView tv_total;
    private TextView tv_open;

    private TextView tv_today;
    private ImageView iv_close;
    private MyUsualyDialog progressDialog;
    private PagerSlidingTabStrip pagerSlidingTabStrip;
    private NestingViewPager viewPager;
    JieDanTools jieDanTools = null;
    private JieDanOrderAdapter pagerAdapter;
    private HashMap<String, String> numMap = new HashMap<>();

    public static DispatchHome newInstance(String tabName) {
        DispatchHome rechargeFragment = new DispatchHome();
        return rechargeFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = (DispatchActivity) getActivity();
        jieDanTools = new JieDanTools(getActivity());
        progressDialog = new MyUsualyDialog(mActivity, R.layout.wait_item);
        progressDialog.setCancelable(false);
        progressDialog.setCanceledOnTouchOutside(false);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        fragmentView = inflater.inflate(R.layout.home_dispatch, container, false);
        return fragmentView;
    }

    @Override
    protected void setTheme() {
        isDrakFont = false;
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        initView();
        new Handler().postDelayed(() -> bindData(), 300);
    }


    /**
     * 初始化布局
     */
    @Override
    public void initView() {
        tv_total = (TextView) findView(R.id.tv_total);
        tv_open = (TextView) findView(R.id.tv_open);

        tv_today = (TextView) findView(R.id.tv_today);
        iv_close = (ImageView) findView(R.id.iv_close);

        tv_open.setText("开始接单");
        iv_close.setVisibility(View.GONE);
        tv_today.setText("0");
        tv_total.setText("0");


        pagerSlidingTabStrip = (PagerSlidingTabStrip) findView(R.id.order_tabs);
        viewPager = (NestingViewPager) findView(R.id.vp_order);

        pagerAdapter = new JieDanOrderAdapter(getChildFragmentManager(), new LiuDanListener() {
            @Override
            public void onBackData(String status, String todayCount, String allCount) {
                Log.e("项目异常", status + "-----onBackData------" + todayCount + "-----onBackData------" + allCount);
                if ("1".equals(status)) {
                    startService();

                } else {
                    stopService();
                }
                tv_today.setText(todayCount); // 今日接单
                tv_total.setText(allCount); // 全部接单
            }

            @Override
            public void onBackNum(String allNum, String liuDanNum, String waitNum) {
                numMap.put("0", waitNum);
                numMap.put("1", liuDanNum);
                numMap.put("2", allNum);
                pagerAdapter.setData(numMap);
            }
        });

        numMap.put("0", "待处理");
        numMap.put("1", "留单");
        numMap.put("2", "全部");

        if (viewPager != null && pagerAdapter != null) {
            pagerAdapter.setData(numMap);
            viewPager.setAdapter(pagerAdapter);
            pagerSlidingTabStrip.setIndicatorHeight(pagerAdapter.getCount());
            viewPager.setOffscreenPageLimit(2);
            pagerSlidingTabStrip.setViewPager(viewPager);
        }

    }

    @Override
    public void bindData() {

        pagerSlidingTabStrip.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                pagerAdapter.fragments.get(position).setPaiDanOrderAdapter(pagerAdapter);

            }

            @Override
            public void onPageSelected(final int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        // 开启接单
        tv_open.setOnClickListener(view -> {
            progressDialog.show();
            jieDanTools.setCurrentState((code, msg) -> {
                Log.e(TAG, "result() called with: code = [" + code + "], msg = [" + msg + "]");
                if (code == 1) {
                    startService();
                } else if (code == 2) {
                    stopService();
                } else if (code == -5) {
                    if (progressDialog != null) {
                        if (!(mActivity.isFinishing() && !mActivity.isDestroyed())) {
                            progressDialog.dismiss();
                        }
                    }
                    Toast.makeText(mActivity, "无法定位您的位置，开启失败！", Toast.LENGTH_SHORT).show();
                } else {
                    if (progressDialog != null) {
                        if (!(mActivity.isFinishing() && !mActivity.isDestroyed())) {
                            progressDialog.dismiss();
                        }
                    }
                    Toast.makeText(mActivity, "开启失败！请重试", Toast.LENGTH_SHORT).show();
                }
            });
        });

        // 关闭接单
        iv_close.setOnClickListener(view -> {
            // 关闭
            progressDialog.show();
            jieDanTools.setCurrentState((code, msg) -> {
                Log.e(TAG, "result() called with: code = [" + code + "], msg = [" + msg + "]");
                if (code == 1) {
                    startService();
                } else if (code == 2) {
                    stopService();
                } else if (code == -5) {
                    Toast.makeText(mActivity, "无法定位您的位置，关闭失败！", Toast.LENGTH_SHORT).show();

                    if (progressDialog != null) {
                        if (!(mActivity.isFinishing() && !mActivity.isDestroyed())) {
                            progressDialog.dismiss();
                        }
                    }
                } else {
                    Toast.makeText(mActivity, "关闭失败！请重试", Toast.LENGTH_SHORT).show();
                    if (progressDialog != null) {
                        if (!(mActivity.isFinishing() && !mActivity.isDestroyed())) {
                            progressDialog.dismiss();
                        }
                    }
                }
            });
        });
    }

    private String mTelNum = "";

    @NeedsPermission(Manifest.permission.CALL_PHONE)
    void needpermission() {
        if (!TextUtils.isEmpty(mTelNum)) {
            Uri uri = Uri.parse("tel:" + mTelNum);
            Intent intent = new Intent();
//                    intent.setAction(Intent.ACTION_DIAL); // 调用拨号盘
            intent.setAction(Intent.ACTION_CALL); // 调用拨号
            intent.setData(uri);
            startActivity(intent);

        }
    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        DispatchHomePermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale(Manifest.permission.CALL_PHONE)
    void showRational(final PermissionRequest request) {
        new AlertDialog.Builder(mActivity)
                .setPositiveButton("允许", (dialog, which) ->
                        request.proceed())
                .setNegativeButton("拒绝", (dialog, which) ->
                        request.cancel())
                .setCancelable(false)
                .setMessage("请允许获取打电话权限")
                .show();
    }

    @OnPermissionDenied(Manifest.permission.CALL_PHONE)
    void Denied() {
//        showErrorDialog("权限不足", "您没有开启此应用的使用打电话权限。请到系统设置-->权限管理 开启打电话使用权限。如果您的手机上安装了第三方应用管家（360管家，腾讯管家等），请开启一下打电话权限！", new DialogInterface.OnDismissListener() {
//            @Override
//            public void onDismiss(DialogInterface dialog) {
//                finish();
//            }
//        });
        ToastUtils.showShortToast(mActivity, "权限不足,您没有开启此应用的使用打电话权限。请到系统设置-->权限管理 开启打电话使用权限。如果您的手机上安装了第三方应用管家（360管家，腾讯管家等），请开启一下打电话权限！");
    }

    @OnNeverAskAgain(Manifest.permission.CALL_PHONE)
    void AskAgin() {
        ToastUtils.showShortToast(mActivity, "权限不足,您没有开启此应用的使用打电话权限。请到系统设置-->权限管理 开启打电话使用权限。如果您的手机上安装了第三方应用管家（360管家，腾讯管家等），请开启一下打电话权限！");
//        showErrorDialog("权限不足", "您没有开启此应用的使用打电话权限。请到系统设置-->权限管理 开启打电话使用权限。如果您的手机上安装了第三方应用管家（360管家，腾讯管家等），请开启一下打电话权限！", new DialogInterface.OnDismissListener() {
//            @Override
//            public void onDismiss(DialogInterface dialog) {
//                finish();
//            }
//        });
    }

    protected void startService() {

        tv_open.setEnabled(false);

        if (!GlobalController.isRuning || !PrefUtils.getBoolean(mActivity, ConstantsValue.PAIDAN_STATE, false)) {
            Intent intent;
            if (GlobalController.isRuning) {
                PrefUtils.setBoolean(getActivity(), ConstantsValue.PAIDAN_STATE, false);
                GlobalController.isRuning = false;
                intent = new Intent(mActivity, DaemonService.class);
                getActivity().stopService(intent);
                Intent intent2 = new Intent(mActivity, PaiDanRemoteService.class);
                getActivity().stopService(intent2);
            }
            PrefUtils.setBoolean(getActivity(), ConstantsValue.PAIDAN_STATE, true);
            GlobalController.isRuning = true;
            intent = new Intent(mActivity, PaiDanRemoteService.class);
            getActivity().startService(intent);

            if (!PrefUtils.getBoolean(mActivity, "BaiMingDan", false)) {
                IntentWrapper.whiteListMatters(getActivity(), "添加到白名单，不能任何进程杀死！");
                PrefUtils.setBoolean(mActivity, "BaiMingDan", true);
            }

        }
        if (progressDialog != null) {
            if (!(mActivity.isFinishing() && !mActivity.isDestroyed())) {
                progressDialog.dismiss();
            }
        }
        tv_open.setText("正在接单中...");
        iv_close.setVisibility(View.VISIBLE);
    }


    protected void stopService() {

        PrefUtils.setBoolean(getActivity(), ConstantsValue.PAIDAN_STATE, false);
        GlobalController.isRuning = false;
        Intent intent = new Intent(mActivity, DaemonService.class);
        getActivity().stopService(intent);
        Intent intent2 = new Intent(mActivity, PaiDanRemoteService.class);
        getActivity().stopService(intent2);
        tv_open.setText("开始接单");
        if (progressDialog != null) {
            if (!(mActivity.isFinishing() && !mActivity.isDestroyed())) {
                progressDialog.dismiss();
            }
        }
        iv_close.setVisibility(View.GONE);
        tv_open.setEnabled(true);
    }


    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
        if (jieDanTools != null) {
            jieDanTools.stopLocation();
            jieDanTools = null;
        }
    }


    @Override
    public void onStop() {
        super.onStop();
        if (progressDialog != null) {
            if (!(mActivity.isFinishing() && !mActivity.isDestroyed())) {
                progressDialog.dismiss();
            }
        }
    }
}
